package com.lovo.atm.service.impl;

import com.lovo.atm.bean.HistoryRecordBean;
import com.lovo.atm.bean.UserBean;
import com.lovo.atm.dao.IHistoryDao;
import com.lovo.atm.dao.IUserDao;
import com.lovo.atm.dao.impls.IHistoryDaoImpls;
import com.lovo.atm.dao.impls.IUserDaoImpls;
import com.lovo.atm.service.IUserService;

/**
 * 业务层用户功能实现
 */

public class IUserServiceImpl implements IUserService {
    private IUserDao iUserDao = new IUserDaoImpls();
    private IHistoryDao iHistoryDao = new IHistoryDaoImpls();

    @Override
    public void saveMoney(String code, double money) {
        iUserDao.update(code, money);
    }

    @Override
    public boolean getMoney(String code, double money) {
        UserBean user = iUserDao.findByName(code);
        if (user.getAccount() < money) {
            return false;
        }
        iUserDao.update(code, user.getAccount()-money);
        iHistoryDao.update(new HistoryRecordBean("取款", money, code));
        return true;
    }

    @Override
    public String transfer(String code, String toName, double money) {
        UserBean user = iUserDao.findByName(code);
        UserBean targetUser = iUserDao.findByName(toName);
        if (targetUser == null) {
            return "账户不存在";
        }
        if (user.getAccount() < money) {
            return "余额不足";
        }
        iUserDao.update(code, user.getAccount()-money);
        iUserDao.update(toName, targetUser.getAccount()+money);
        iHistoryDao.update(new HistoryRecordBean("转出"+toName, money, code));
        iHistoryDao.update(new HistoryRecordBean("转入"+toName, money, code));
        return "转账成功";
    }

    @Override
    public UserBean findByCode(String code) {
        return iUserDao.findByName(code);
    }

    @Override
    public UserBean login(String name, String pwd) {
        return  iUserDao.login(name, pwd);
    }
}
